package com.gjy.netty.http.helloworld;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-02-21 16:49:40
 */
public class HttpHelloWorldServer {

    private static final Integer PORT = 8080;

    public static void main(String[] args) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap sbs = new ServerBootstrap();
            sbs.group(bossGroup, workGroup)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new ChannelInboundHandlerAdapter() {
                                private final byte[] CONTENT = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};

                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    if (msg instanceof HttpRequest) {
                                        HttpRequest req = (HttpRequest) msg;
                                        if (HttpUtil.is100ContinueExpected(req)) {
                                            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
                                        }
                                        boolean keepAlive = HttpUtil.isKeepAlive(req);
                                        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
                                        response.headers().set(CONTENT_TYPE, "text/plain");
                                        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

                                        if (!keepAlive) {
                                            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
                                        } else {
                                            response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
                                            ctx.write(response);
                                        }
                                    }
                                }
                            });
                        }
                    });
            Channel channel = sbs.bind(PORT).sync().channel();
            channel.closeFuture().sync();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
